<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 订单管理
 * @author Administrator
 *
 */
class Order extends MY_Controller {

	/**
	 * @var DlnUserModel
	 */
	public  $mMember = null;
	
	/**
	 * @var DlnOrderModel
	 */
	public  $mOrder = null;
	
	public function __construct(){
		parent::__construct();	
		$this->loadModel('DlnUserModel', 'mMember', 'deliveryman');
		$this->loadModel('DlnOrderModel', 'mOrder', 'deliveryman');
	}
	
	/**
	 * 首页
	 */
	public function index(){
		$this->loadModel('AdmSettingModel', 'mSetting', 'admin');
		$data = [
				'status' => $this->mOrder->status(),
				'type' => $this->mOrder->type(),
				'apconfig' => $this->mOrder->apConfig(),
				'province' => $this->mSetting->getProvinces()
		];
		$this->view('deliveryman/order/home', $data,'datatable,datepicker,select2');
	}

	/**
     * 列表
     */
	public function getList(){
        $this->loadModel('ConsumerOrderModel', 'mConOrder', 'consumer');

		$dateFrom = get('date_from');
		$dateTo = get('date_to');
		$code = trim(get('code'));
		$sendUser = trim(get('send_user'));
		$sendMobile = trim(get('send_mobile'));
		$sendToUser = trim(get('send_to_user'));
		$sendToMobile = trim(get('send_to_mobile'));
		$sendAddress = trim(get('send_address'));
		$sendToAddress = trim(get('send_to_address'));
		$deliveryman = trim(get('deliveryman'));
		$deliverymanMobile = trim(get('deliveryman_mobile'));
		$status = (int)get('status');
		$type = (int)get('type');
		$apStatus = (int)get('ap_status');
		$province = get ( 'province' );
		$city = get ( 'city' );
		$county = get ( 'county' );
		
		$this->db->select('o.id,o.code,o.send_user,o.send_address, o.send_mobile,
				o.province_id,o.city_id,o.county_id,u.province_id as u_province_id,u.city_id as u_city_id,
				u.county_id as u_county_id,
				o.distance,o.send_to_mobile,o.status,o.addtime,co.expect_arrive_time,o.rob_expect_time,u.name,
				u.mobile,o.type,o.income,o.complete_time,ap.type as ap_type,ap.content as ap_content')
				->join($this->mOrder->tbRelationOrder.' ro', 'ro.order_id = o.id', 'left')
				->join($this->mMember->tbUser.' u', 'u.id = ro.deliveryman_id', 'left')
				->join($this->mOrder->tbOrderAp.' ap', 'ap.order_id = o.id', 'left')
				->join($this->mConOrder->tbOrder.' co', 'o.order_id = co.id')
				->order_by('o.id desc');
		
		if($province){
			$this->db->where('((o.status = 1 and o.province_id = '.$province.')
			or (u.id > 1 and u.province_id = '.$province.'))');
		}
		
		if($city){
			$this->db->where('((o.status = 1 and o.city_id = '.$city.')
			or (u.id > 1 and u.city_id = '.$city.'))');
		}
		
		if($county && $county[0] && is_array($county)){
			$this->db->where_in('o.county_id', $county);
			$this->db->where('((o.status = 1 and o.county_id in ('.implode(',', $county).'))
			or (u.id > 1 and u.county_id in ('.implode(',', $county).')))');
		}
		
		if($dateFrom){
			$this->db->where('o.addtime >=', strtotime($dateFrom));
		}
		
		if($dateTo){
			$this->db->where('o.addtime <', strtotime('+1day', strtotime($dateTo)));
		}
		
		if($code){
			$this->db->where('o.code', $code);
		}
		
		
		if($status){
			$this->db->where('o.status', $status);
		}
		
		if($sendUser){
			$this->db->like('o.send_user', $sendUser);
		}
		
		if($sendMobile){
			$this->db->where('o.send_mobile', $sendMobile);
		}
		
		if($sendToUser){
			$this->db->like('o.send_to_user', $sendToUser);
		}
		
		if($sendToMobile){
			$this->db->where('o.send_to_mobile', $sendToMobile);
		}
		
		if($sendAddress){
			$this->db->like('o.send_address', $sendAddress);
		}
		
		if($sendToAddress){
			$this->db->like('o.send_to_address', $sendToAddress);
		}
		
		if($type){
			$this->db->where('o.type', $type);
		}
		
		if($deliveryman){
			$this->db->like('u.name', $deliveryman);
		}
			
		if($deliverymanMobile){
			$this->db->where('u.mobile', $deliverymanMobile);
		}
		
		if($apStatus){
			$this->db->where('ap.type', $apStatus);
		}
		
		$data = $this->mMember->pagination($this->mOrder->tbOrder.' o');
		$addressId = [];
		foreach ($data['data'] as $v){
			if( ! in_array($v['province_id'], $addressId)){
				$addressId[] = $v['province_id'];
			}
			if( ! in_array($v['city_id'], $addressId)){
				$addressId[] = $v['city_id'];
			}
			if( ! in_array($v['county_id'], $addressId)){
				$addressId[] = $v['county_id'];
			}
			if( ! in_array($v['u_province_id'], $addressId)){
				$addressId[] = $v['u_province_id'];
			}
			if( ! in_array($v['u_city_id'], $addressId)){
				$addressId[] = $v['u_city_id'];
			}
			if( ! in_array($v['u_county_id'], $addressId)){
				$addressId[] = $v['u_county_id'];
			}
		}
		
		$this->loadModel('AdmSettingModel', 'mSett', 'admin');
		$address = $this->mSett->getLocationNameByIds($addressId);
        foreach ($data['data'] as $k => $v){
        	
        	if($v['distance'] > 1000){
        		$v['distance'] = ($v['distance'] / 1000).'km';
        	}else{
        		$v['distance'] = $v['distance'].'m';
        	}
        	
            $data['aaData'][$k][] = dateFormat($v['addtime'], true);
            $data['aaData'][$k][] = $v['code'];
//             $data['aaData'][$k][] = $v['send_user'].'<br/><span style="color:grey;">（'.$v['send_mobile'].'）</span>';
//             $data['aaData'][$k][] = $v['send_to_user'].'<br/><span style="color:grey;">（'.$v['send_to_mobile'].'）</span>';
            $tS = '';
            if($v['status'] == 1){
            	$tS = isset($address[$v['province_id']]) ? $address[$v['province_id']]['name'] : '';
            	$tSs = isset($address[$v['city_id']]) ? $address[$v['city_id']]['name'] : '';
            	$tS .= $tSs == $tS ? '' : $tSs;
            	$tS .= isset($address[$v['county_id']]) ? $address[$v['county_id']]['name'] : '';
            }else{
            	$tS = isset($address[$v['u_province_id']]) ? $address[$v['u_province_id']]['name'] : '';
            	$tSs = isset($address[$v['u_city_id']]) ? $address[$v['u_city_id']]['name'] : '';
            	$tS .= $tSs == $tS ? '' : $tSs;
            	$tS .= isset($address[$v['u_county_id']]) ? $address[$v['u_county_id']]['name'] : '';
            }
            
            $data['aaData'][$k][] = $tS;
            $data['aaData'][$k][] = $v['mobile'] ? $v['name'].'<br/><span style="color:grey;">（'.$v['mobile'].'）</span>' : '';
//             $data['aaData'][$k][] = $v['send_address'];
//             $data['aaData'][$k][] = $v['send_to_address'];
            $data['aaData'][$k][] = $v['distance'];
            $data['aaData'][$k][] = $v['income'];
            $data['aaData'][$k][] = $this->mOrder->type($v['type']);
            $tI = ceil((($v['status'] == 4 ? $v['complete_time'] : time()) - 
            		($v['status'] == 1 ? $v['rob_expect_time'] : $v['expect_arrive_time'])) / 60);
            $show  = '';
            if(abs($tI) < 60){
            	$show = abs($tI).'分钟';
            }elseif(abs($tI) > 60){
            	$e = abs($tI) % 60;
            	$show = floor(abs($tI) / 60).'小时';
            	if($e > 0){
            		$show .= $e.'分钟';
            	}
            }
            
            if($tI > 0){
            	if($v['status'] == 4){
	            	$show = '超时'.$show;
            	}else{
	            	$show = '已超时'.$show;
            	}
            }else{
            	if($v['status'] == 4){
            		$show = '提前'.$show.'送达';
            	}else{
            		$show = $show.'后超时';
            	}
            }
            
            $data['aaData'][$k][] = $v['status'] != 5 ? $show : '';
            $data['aaData'][$k][] = $v['ap_type'] > 0 ? $this->mOrder->apConfig($v['ap_type'])
            .'<br/><a class="ap-content-btn" href="javascript:void(0);"><span class="type">查看备注</span>
            		<span class="content hide">'.nl2br($v['ap_content']).'</span></a>' : '未报备';
            $data['aaData'][$k][] = $this->mOrder->status($v['status'], true);
            $btnConfig = array(
            		array(
            				'label' => '详情',
            				'icon' => '<i class="fa fa-eye"></i>',
            				'attr' => array(
            						'href' => getUrl('deliveryman/order/details?id='.$v['id']),
            						'class' => 'btn btn-xs btn-default',
            				),
            				'tag' => 'a'
            		),
            );
            
            $data['aaData'][$k][] = adminCreateBtn($btnConfig);
        }
        unset($data['data']);
        echo json_encode($data);
    }
    
    /**
     * 订单详情
     */
    public function details(){
    	
    	$this->loadModel('AdmSettingModel', 'mSett', 'admin');
    	$id = get('id');	
    	if( ! $id){
    		show_404();
    	}
    	
    	$info = $this->mOrder->getInfo($id, 0, true);
    	if( ! $info){
    		show_404();
    	}
    
    	$info['statusStr'] = $this->mOrder->status($info['status']);
    	$info['ap'] = $this->mOrder->getApInfo($id);
    	$info['ak'] = $this->mSett->get('map_key','deliveryman');
    	$this->view('deliveryman/order/detail', $info);
    }
}
